<template>
  <div class="orders-container page-view">
    <div class="orders-header header-section">
      <h1 class="page-title">
        <i class="bi bi-cart me-2"></i>
        订单管理
      </h1>
      <p class="page-subtitle">管理客户订单和交易记录</p>
    </div>

    <div class="orders-content">
      <!-- 统计卡片 -->
      <div class="row mb-4">
        <div class="col-md-3 mb-3">
          <div class="card text-center">
            <div class="card-body">
              <h5 class="card-title text-primary">{{ orderStats.total }}</h5>
              <p class="card-text">总订单数</p>
            </div>
          </div>
        </div>
        <div class="col-md-3 mb-3">
          <div class="card text-center">
            <div class="card-body">
              <h5 class="card-title text-success">{{ orderStats.completed }}</h5>
              <p class="card-text">已完成</p>
            </div>
          </div>
        </div>
        <div class="col-md-3 mb-3">
          <div class="card text-center">
            <div class="card-body">
              <h5 class="card-title text-warning">{{ orderStats.pending }}</h5>
              <p class="card-text">待处理</p>
            </div>
          </div>
        </div>
        <div class="col-md-3 mb-3">
          <div class="card text-center">
            <div class="card-body">
              <h5 class="card-title text-danger">{{ orderStats.cancelled }}</h5>
              <p class="card-text">已取消</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选和搜索（Element Plus） -->
      <div class="header-section">
        <div class="search-section">
          <el-input v-model="searchQuery" placeholder="搜索订单号或客户..." clearable class="w-300 mr-16">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select v-model="selectedStatus" placeholder="全部状态" clearable class="w-150 mr-16">
            <el-option label="全部状态" value="" />
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>

        <el-button type="primary">导出订单</el-button>
      </div>

      <!-- 订单列表（Element Plus） -->
      <el-card class="table-card">
        <el-table :data="displayedOrders" stripe style="width: 100%" empty-text="暂无数据">
          <el-table-column label="订单号" min-width="180">
            <template #default="{ row }">
              <el-text type="primary" class="fw-bold">{{ row.orderNo }}</el-text>
            </template>
          </el-table-column>

          <el-table-column label="客户" min-width="180">
            <template #default="{ row }">
              <div class="customer-info">
                <div class="customer-name">{{ row.customer.name }}</div>
                <div class="customer-phone">
                  <el-text type="info" size="small">{{ row.customer.phone }}</el-text>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="商品" min-width="220">
            <template #default="{ row }">
              <div class="order-items">
                <div v-for="item in row.items.slice(0, 2)" :key="item.id" class="item-row">
                  {{ item.name }} x{{ item.quantity }}
                </div>
                <el-text v-if="row.items.length > 2" type="info" size="small">等{{ row.items.length }}件商品</el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="金额" width="120" align="center">
            <template #default="{ row }">
              <el-text type="primary">¥{{ row.totalAmount }}</el-text>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === 'pending'
                    ? 'warning'
                    : row.status === 'processing'
                      ? 'info'
                      : row.status === 'completed'
                        ? 'success'
                        : 'danger'
                "
                size="small"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="支付方式" width="120" align="center">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.paymentMethod }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="下单时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewOrder(row)">查看</el-button>
              <el-button v-if="row.status === 'pending'" size="small" type="success" @click="processOrder(row.id)">
                处理
              </el-button>
              <el-button v-if="row.status !== 'cancelled'" size="small" type="danger" @click="cancelOrder(row.id)">
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页（Element Plus） -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { Search } from "@element-plus/icons-vue";

defineOptions({
  name: "OrdersView",
});

// 响应式数据
const searchQuery = ref("");
const selectedStatus = ref("");

// 订单统计
const orderStats = ref({
  total: 1256,
  completed: 1089,
  pending: 89,
  cancelled: 78,
});

// 模拟订单数据
const orders = ref([
  {
    id: 1,
    orderNo: "ORD202401150001",
    customer: {
      name: "张三",
      phone: "138****8888",
    },
    items: [
      { id: 1, name: "iPhone 15 Pro", quantity: 1 },
      { id: 2, name: "AirPods Pro", quantity: 1 },
    ],
    totalAmount: "8899.00",
    status: "completed",
    paymentMethod: "微信支付",
    createdAt: "2024-01-15T10:30:00Z",
  },
  {
    id: 2,
    orderNo: "ORD202401150002",
    customer: {
      name: "李四",
      phone: "139****9999",
    },
    items: [{ id: 3, name: "MacBook Air M2", quantity: 1 }],
    totalAmount: "8999.00",
    status: "pending",
    paymentMethod: "支付宝",
    createdAt: "2024-01-15T11:20:00Z",
  },
  {
    id: 3,
    orderNo: "ORD202401150003",
    customer: {
      name: "王五",
      phone: "137****7777",
    },
    items: [
      { id: 4, name: "Nike Air Max", quantity: 2 },
      { id: 5, name: "Adidas Ultra Boost", quantity: 1 },
    ],
    totalAmount: "2697.00",
    status: "processing",
    paymentMethod: "银行卡",
    createdAt: "2024-01-15T09:45:00Z",
  },
  {
    id: 4,
    orderNo: "ORD202401140001",
    customer: {
      name: "赵六",
      phone: "136****6666",
    },
    items: [{ id: 6, name: "《Vue.js 设计与实现》", quantity: 3 }],
    totalAmount: "267.00",
    status: "cancelled",
    paymentMethod: "微信支付",
    createdAt: "2024-01-14T16:30:00Z",
  },
]);

// 计算属性
const filteredOrders = computed(() => {
  return orders.value.filter((order) => {
    const matchesSearch =
      order.orderNo.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      order.customer.name.toLowerCase().includes(searchQuery.value.toLowerCase());
    const matchesStatus = !selectedStatus.value || order.status === selectedStatus.value;
    return matchesSearch && matchesStatus;
  });
});

// 本地分页状态
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 当前页数据
const displayedOrders = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize;
  return filteredOrders.value.slice(start, start + pagination.value.pageSize);
});

// 监听过滤结果更新总数并重置页码
watch(filteredOrders, (list) => {
  pagination.value.total = list.length;
  pagination.value.page = 1;
});

// 分页事件
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
};

// 方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString("zh-CN");
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待处理",
    processing: "处理中",
    completed: "已完成",
    cancelled: "已取消",
  };
  return statusMap[status] || status;
};

const viewOrder = (order: any) => {
  console.log("查看订单详情:", order);
};

const processOrder = (id: number) => {
  const order = orders.value.find((o) => o.id === id);
  if (order) {
    order.status = "processing";
    console.log("处理订单:", id);
  }
};

const cancelOrder = (id: number) => {
  if (confirm("确定要取消这个订单吗？")) {
    const order = orders.value.find((o) => o.id === id);
    if (order) {
      order.status = "cancelled";
      console.log("取消订单:", id);
    }
  }
};

onMounted(() => {
  console.log("订单管理页面加载完成");
});
</script>

<style scoped>
.orders-container {
  padding: 2rem;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.orders-header {
  margin-bottom: 2rem;
}

.page-title {
  color: #5a5c69;
  font-size: 1.75rem;
  font-weight: 400;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  color: #858796;
  margin-bottom: 0;
}

.customer-info {
  min-width: 120px;
}

.customer-name {
  font-weight: 600;
  color: #5a5c69;
}

.order-items {
  min-width: 200px;
}

.item-row {
  font-size: 0.9rem;
  color: #5a5c69;
}

.card {
  border: none;
  border-radius: 0.35rem;
}

.shadow {
  box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
}

.btn-group .btn {
  margin-right: 0.25rem;
}

.btn-group .btn:last-child {
  margin-right: 0;
}
</style>
